/*
 * Created by IntelliJ IDEA.
 * User: amrk
 * Date: 8/02/2004
 * Time: 10:56:48
 */
package com.talios.jira.idea.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.ui.popup.ListPopupStep;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.talios.jira.browser.IssueManager;
import com.talios.jira.browser.JiraItem;
import com.talios.jira.browser.JiraMonitorPanel;
import com.talios.jira.feeds.FeedException;
import com.talios.jira.feeds.MyIssuesFeedBuilder;
import com.talios.jira.idea.JiraConfigurationComponent;

import java.util.*;

/**
 * @jira INTPLUG-157 Should query assigned issues directly, independant of any IssueBrowserPanel
 */
public class WorkOnIssueAction extends JIRAAction {
    private static final Logger LOGGER = Logger.getInstance("Jira Browser");

    /**
     * @jira INTPLUG-43 Add a quick work-on-action lookup
     * @jira INTPLUG-44 NullPointer selecting WorkOnIssue action when no project setup
     * @jira INTPLUG-157 Should query assigned issues directly, independant of any IssueBrowserPanel
     */
    public void actionPerformed(AnActionEvent event) {

        final Project project = (Project) event.getDataContext().getData(DataConstants.PROJECT);
        final JiraConfigurationComponent config = project.getComponent(JiraConfigurationComponent.class);
        JiraMonitorPanel monitor = config.getJiraMonitor();

        if (monitor == null) return;

        final List<JiraItem> assignedIssues = new ArrayList<JiraItem>(getAssignedIssues(project));

        Collections.sort(assignedIssues, new Comparator<JiraItem>() {
            public int compare(JiraItem o1, JiraItem o2) {
                return o1.getKeyValue().compareTo(o2.getKeyValue());
            }
        });


        ListPopupStep popupStep = new BaseListPopupStep<JiraItem>("Work on Issue", assignedIssues) {
            public PopupStep onChosen(JiraItem jiraItem, boolean b) {
                config.setItemWorkedOn(jiraItem);
                IssueManager.getInstance().startWorkOnIssue(project, jiraItem);
                return null;
            }
        };

        ListPopup listPopup = new ListPopupImpl(popupStep);
        listPopup.showCenteredInCurrentWindow(project);
    }

    private Set getAssignedIssues(Project project) {
        Set assignedIssues = new HashSet();
        if (project != null) {
            MyIssuesFeedBuilder fb = new MyIssuesFeedBuilder(project);

            try {
                assignedIssues = fb.buildFeedData();
            } catch (FeedException e) {
                LOGGER.error("Unable to find issues", e);
            }
        }
        return assignedIssues;
    }

}